package com.fire.security.service.impl;



import com.fire.security.domain.Result;
import com.fire.security.domain.Shop;
import com.fire.security.mapper.ShopMapper;
import com.fire.security.service.ShopService;
import com.fire.security.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;


import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

//@CacheConfig(cacheNames = "com.fire.shop.service.impl.ShopServiceImpl")
@Service
public class ShopServiceImpl implements ShopService {

    // 注入ShopMapper
    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * <h2>通过id查询所有商铺</h2>
     * */
    @Override
    public List<Shop> queryShopById(String id) {
        return null;
    }

    /**
    * //查询所有shop的方法
    List<Shop> queryAllShop();
    * 对查询到的所有shop进行缓存，缓存到redis的键为all:store
    * */
//    @Cacheable(key = "'all:shop'")
    @Override
    public List<Shop> queryAllShop(Shop shop) {
        // 查询所有shop
        return shopMapper.queryAllShop(shop);
    }

    /**
     * <h2>
     *     根据user id查询所有shop
     * </h2>
     * */
    @Override
    public List<Shop> queryShopByUserId(String userId) {
         // 查询
        return shopMapper.queryShopByUserId(userId);
    }


    /**
    * //根据shop id删除仓库的方法
    Result deleteById(Integer id);
    *
     * @return*/
    @Override
    public Result deleteById(String id) {
        // 根据id删除shop
        int i = shopMapper.deleteById(id);
        if (i > 0) {
            return Result.ok("商铺删除成功！");
        }
        return Result.err(501, "商铺删除失败！");
    }

    /**
    * //根据shop id修改仓库的方法
    Result updateById(Shop shop);
    * */
    @Override
    public Result updateById(Shop shop) {
        // 根据id修改商铺信息
        int i = shopMapper.updateById(shop);
        if (i > 0) {
            return Result.ok("商铺信息修改成功！");
        }
        return Result.err(501, "商铺信息修改失败！");
    }

    /**
    * //添加shop的方法
     Result insert(Shop shop);
    * */
    @Override
    public Result insert(Shop shop) {
        int i = shopMapper.insert(shop);
        if (i > 0) {
            if (!stringRedisTemplate.hasKey("todayShop")){
                stringRedisTemplate.opsForValue().set("todayShop", String.valueOf(1), DateUtils.getTimeDifference(new Date()), TimeUnit.SECONDS);
            }else {
                int todayShop = Integer.parseInt(stringRedisTemplate.opsForValue().get("todayShop"));
                stringRedisTemplate.opsForValue().set("todayShop", String.valueOf(todayShop+1), DateUtils.getTimeDifference(new Date()), TimeUnit.SECONDS);
            }
            return Result.ok("商铺添加成功！");
        }
        return Result.err(501, "商铺添加失败！");
    }

}
